# coding=utf-8
# 第一版 2022/3/21 author: ylong52@21cn.com
from http import server
from lib2to3.pgen2 import driver
from urllib.parse import urlparse
from myselenium import *
import sys
from LocalStorage import *
from browsermobproxy import Server
import json

class artMain:
    #解决占用端口
    def kill_process(self,port):
        # os.system('taskkill /im chromedriver.exe /F')
        # os.system('taskkill /im chrome.exe /F')

        ret = os.popen("netstat -nao|findstr '"+str(port)+"'")    
        #注意解码方式和cmd要相同，即为"gbk"，否则输出乱码
        str_list = ret.read() 
        time.sleep(0.5)
        ret_list = re.split('',str_list)
        try:
            process_pid = list(ret_list[0].split())[-1]
            os.popen('taskkill /pid ' + str(process_pid) + ' /F')
            print("端口已被释放")
        except:
            #print("端口未被使用")
            return True

        #读ini文件  
    def getGoodINIUrl(self):
        cfg1 = "config.ini"
        conf = configparser.ConfigParser()
        conf.read(cfg1, encoding="utf-8-sig")
        self.config = conf
        #读取ini文件中的内容
        # price = conf.get("goods", "price")
        # goodsurl = conf.get("goods", "goodsurl")    



    #主程序
    def __init__(self):      
        self.kill_process(8090);
        self.getGoodINIUrl()  
        dict={'port':8090} #browsermob-proxy端口
        #server = Server(r'.\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat') 
        sserver = Server(r".\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat",options=dict)                
        sserver.start()
        proxy = sserver.create_proxy()    
        self.proxy = proxy
        chrome_options2 = Options()
        
         
        if ("1" != self.config.get("setup", "viewgoogle")):
            chrome_options2.add_argument('--headless') #无头浏览器

        chrome_options2.add_argument('--disable-gpu')
        chrome_options2.add_argument('--ignore-certificate-errors')
        chrome_options2.add_argument('--ignore-ssl-errors')
        chrome_options2.add_argument('--proxy-server={0}'.format(proxy.proxy))

        prefs = {"profile.managed_default_content_settings.images": 2}
        chrome_options2.add_experimental_option("prefs", prefs)

        driver = webdriver.Chrome(options=chrome_options2)
        driver.set_window_size(500,800)
        driver.get('https://artmeta.cn/')

        self.driver = driver

        self.loginAccount()
        
 
        


    def loginAccount(self):
        
        storage = LocalStorage(self.driver)
        
        # storage["truename"] = '刘洋'
        # storage["UserLoginToken"] = '{"type":"object","data":{"AccessTokenKey":"510bf47c-3a98-4091-851a-b5503d45b62c","AccessTokenExpiresTime":1647844560,"RefreshTokenKey":"68c3de79-0766-4afa-8a38-7198b585f9cb","RefreshTokenExpiresTime":1647844560}}'
        # storage["userinfo"] = '{"type":"object","data":{"UserId":208699,"UserName":"adc","AvatarUrl":"https://images.cang.com/CommImg/comm/nft_avatar_default.png","Phone":"18694064658","Nickname":null,"CreateTime":"2022-02-28T00:37:37","UserStatus":1,"IsSetTradePassword":1,"IsAuthRealName":1,"TrueName":"刘洋","IsAddBank":0,"IsAuthEmail":0,"EmailAddress":null,"IsArtist":0}}'
        # storage["UserId"] = '{"type":"number","data":208699}'

        storage["truename"] = self.config.get("login", "truename")
        storage["UserLoginToken"] = self.config.get("login", "UserLoginToken")
        storage["userinfo"] =  self.config.get("login", "userinfo")       
        print('登录中......')
 
        self.driver.get('https://artmeta.cn/pages/usercenter/usercenter')
        time.sleep(1)
        if(storage.get("truename")==None):
            print('帐号登录登录失败!!!!!')
            time.sleep(10)
            self.driver.quit()
            sys.exit()
        else:
            print('帐号登录成功 >>>')
            self.derivativedetail()
            
            return True   

    
        # if _txt:
        #    _txt2 = valclass(driver, 'user-id') 
        #    print('个人中心')
        
        # else:
        #     print('登录失败')



    #找到转售市场
    def derivativedetail(self):
        # url = 'https://artmeta.cn/pages/derivativedetail/derivativedetail?id=131138'     
        #proxy.new_har(url)
        self.proxy.new_har("huaruntong", options={'captureHeaders': True, 'captureContent': True})
        self.driver.get(self.config.get("goods","goodsurl"))

        time.sleep(1)
        tapid(self.driver,'u-tab-item-1')   #换到tab页面
        result = self.driver.find_element(By.CLASS_NAME, 'list')
        time.sleep(1)
        if (result == False):
            raise SelfExceptionError("未找到转到市场的按钮")

        # element1 = WebDriverWait(self.driver,3).until(
        #     EC.presence_of_element_located((By.CLASS_NAME, "nft-icon-down"))
        # )
        # element1.send_keys(Keys.PAGE_DOWN)   

        for i in range(2):
            print(f'第{i+1}页>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n')
            item_id2 = self.getHarUrl(self.proxy.har)
            
            #mouse滚轮向下翻页  
            js="window.scrollTo(0,document.body.scrollHeight)"
            self.driver.execute_script(js)
            # print(f'共输出条:{self.countList}记录')  
            
            # time.sleep(1)

        
        # element1 = WebDriverWait(driver, 15).until(
        #         EC.presence_of_element_located((By.CLASS_NAME, "u-tab-item-1"))
        #     )
        
        # element1.send_keys(Keys.PAGE_DOWN)  
               
        print('end <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
        # driver.quit()

    #取包
    def getHarUrl(self,result):
        
        for entry in result['log']['entries']:
            _url = entry['request']['url']
            if "https://api.artmeta.cn/api.ashx" in _url:
                # print(">>>>>>>>>>"+_url+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
                _response = entry['response']
                _content = _response['content']
                # print("_content>>>>>>>>>>>>>>>>>\n\n")
                # print(_url)
                # print(_content)
                if "GoodsGroupSerialNoStr" in json.dumps(_content):
                    self.dataout(_content)
                #print(entry)
                #print("<<<< url end <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
        # print("<<<< url end <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")

    
    ##分析接口数据
    def dataout(self,data):
        _filter_price = self.config.get("goods","price")  #最低的价格
        _filter_price = to_int(_filter_price)
        # print("_filter_price = ")
        # print(_filter_price)
        #json.dumps将python对象格式化成json字符（将dict转化成str）
        #json.loads将json字符串解码成python对象（将str转化成dict）
        _dict = json.loads(data['text'])
        _datalist = _dict.get('Data')['Data'] #datalist是dict类型 
        _find_num = 0
        _countList = 0
        for i in _datalist:

            #print("id:"+str(i['GoodsId'])+",name:"+i['GoodsName']+",price:"+str(i['GoodsPrice'])+"\n")
            if (_filter_price>0):
                if (to_int(i['GoodsPrice'])<=_filter_price):
                    # print("id:"+str(i['GoodsId'])+",name:"+i['GoodsName']+",price:"+str(i['GoodsPrice'])+"\n")
                    self.worksdetail(i['GoodsId'])
                    _find_num +=1
                    _countList+=1
                    self.driver.quit()
                    sys.exit()
                    break
            else:
               _countList+=1
               print("No."+str(_countList)+",id:"+str(i['GoodsId'])+",name:"+i['GoodsName']+",price:"+str(i['GoodsPrice']))
        print("\n\n")
        self.countList = _countList
        if (_find_num==0 and _filter_price>0):
            print("未找到符合条件的商品ID"+str(i['GoodsId']))
        return False
        
    
    #购买页面
    def worksdetail(self,item_id):
    
        url = "https://artmeta.cn/pages/worksdetail/worksdetail?id="+str(item_id)
        self.driver.get(url)
        element = WebDriverWait(self.driver,3,0.3).until(
            EC.presence_of_element_located((By.CLASS_NAME, "works-offer-purchase"))
        )
        element.click()
        element2 = WebDriverWait(self.driver,3,0.1).until(
            EC.presence_of_element_located((By.CLASS_NAME, "next"))
        )
        time.sleep(0.3)
        element2.click()
        #点“购买”按钮,默认选的支付宝
        try:
            element3 = WebDriverWait(self.driver,3,0.1).until(
                EC.presence_of_element_located((By.CLASS_NAME, "pay"))
            )
            time.sleep(0.3)
            element3.click()
        except:    
            if "worksdetail" in self.driver.current_url:
                print("\n\n￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣")
                print("支付失败！！！！！！,估计是账户被锁12小时。手工去查看个人中心 !!!!!\n\n")
                self.driver.quit()
                sys.exit()             
            if "cashier" in self.driver.current_url:
                print("\n\n￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣")
                print("已经点了立即支付，请去个人中心付款\n")
                print("⊙▽⊙ ⊙▽⊙ ⊙▽⊙ \n\n")
                self.driver.quit()
                sys.exit() 
            
            
        

#-------------------- start 
artMain()
 


